/**   
 * @Title: PublicController.java
 * @Package com.julie.edu.controller
 * @Description: TODO(用一句话描述该文件做什么)
 * @author longfei
 * @date 2015-6-4 上午10:49:30
 * @version V1.0
 */
package com.qinghe.pro.controller.main;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.qinghe.pro.entity.main.Module;
import com.qinghe.pro.service.main.ModuleService;
import com.qinghe.pro.shiro.ShiroUser;
import com.qinghe.utils.SecurityUtils;

@Controller
@RequestMapping("/public")
public class PublicController {

	@Autowired
	@Qualifier("moduleServiceImpl")
	protected ModuleService moduleService;

	private static final String HEADER = "/manager/public/header";
	private static final String LEFT = "/manager/public/left";

	@RequestMapping(value = "/header", method = { RequestMethod.GET, RequestMethod.POST })
	public String header(String tag, Map<String, Object> map) {
		ShiroUser shiroUser = SecurityUtils.getShiroUser();
		// 得到有权限的模块菜单
		Module menuModule = getMenuModule(SecurityUtils.getSubject());

		map.put("tag", tag);
		map.put("login_user", shiroUser);
		map.put("menuModule", menuModule);
		return HEADER;
	}

	@RequestMapping(value = "/left", method = { RequestMethod.GET, RequestMethod.POST })
	public String left(String tag, String tag1, Map<String, Object> map) {
		// 得到有权限的模块菜单
		Module menuModule = getMenuModule(SecurityUtils.getSubject());

		map.put("tag", tag);
		map.put("tag1", tag1);
		map.put("menuModule", menuModule);
		return LEFT;
	}

	/**
	 * 模块菜单
	 * 
	 * @param subject
	 * 
	 * @return
	 * @author longfei
	 */
	private Module getMenuModule(Subject subject) {
		Module rootModule = moduleService.getTree();

		check(rootModule, subject);
		return rootModule;
	}

	/**
	 * 过滤权限模块
	 * 
	 * @param module
	 * @param subject
	 * 
	 * @return
	 * @author longfei
	 */
	private void check(Module module, Subject subject) {
		List<Module> modules = new ArrayList<Module>();
		for (Module m1 : module.getChildren()) {
			// 只加入拥有show权限的Module
			if (subject.isPermitted(m1.getSn() + ":show")) {
				check(m1, subject);
				modules.add(m1);
			}
		}
		module.setChildren(modules);
	}

}
